import {FormControl, FormGroup} from '@angular/forms';
import {GnValidatorMessage, GnValidators} from '../validator';

export class GnFormUtils {

  static ensureFormControl(formGroup: FormGroup, field: string, validators: GnValidatorMessage[]): FormControl {
    const fields = field.split('.');
    if (fields.length === 1) {
      let formControl = formGroup.controls[field] as FormControl;
      if (!formControl) {
        if (!validators) {
          validators = [];
        }
        formControl = new FormControl(null, validators.map((value) => {
          const validator = GnValidators[value.validator];
          return validator(formGroup, value.validatorArgs);
        }));
        formGroup.addControl(field, formControl);
      }
      return formControl;
    } else {
      const currentField = fields[0];
      let currentFormGroup = formGroup.controls[currentField] as FormGroup;
      if (!currentFormGroup) {
        currentFormGroup = new FormGroup({});
        formGroup.addControl(currentField, currentFormGroup);
      }

      fields.splice(0, 1);
      const restField = fields.join('.');
      return GnFormUtils.ensureFormControl(currentFormGroup, restField, validators);
    }
  }

  static removeFormControl(formGroup: FormGroup, field: string): void {
    const fields = field.split('.');
    if (fields.length === 1) {
      if (formGroup.contains(fields[0])) {
        formGroup.removeControl(fields[0]);
      }
    } else {
      const currentField = fields[0];
      if (formGroup.contains(currentField)) {
        const currentFormGroup = formGroup.controls[currentField] as FormGroup;
        fields.splice(0, 1);
        const restField = fields.join('.');
        GnFormUtils.removeFormControl(currentFormGroup, restField);
        if (currentFormGroup.value === {}) {
          formGroup.removeControl(currentField);
        }
      }
    }
  }

}
